package cn.zn.wx.interceptor;


import cn.hutool.core.util.StrUtil;
import cn.zn.framework.common.exception.RRException;
import cn.zn.modules.zzsys.inter.annotation.Login;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
public class AuthorizationInterceptor extends HandlerInterceptorAdapter {

    public static final String TOKEN = "token";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Login annotation;
        if (handler instanceof HandlerMethod) {
            annotation = ((HandlerMethod) handler).getMethodAnnotation(Login.class);
        } else {
            return true;
        }

        if (annotation == null) {
            return true;
        }

        //获取用户凭证
        String token = request.getHeader(TOKEN);
        if (StrUtil.isBlank(token)) {
            Cookie[] cookies = request.getCookies();
            if (cookies != null) {
                for (Cookie cookie : cookies) {
                    if (cookie.getName().equalsIgnoreCase(TOKEN)) {
                        token = cookie.getValue();
                        break;
                    }
                }
            }
        }
        if (StrUtil.isBlank(token)) {
            token = request.getParameter(TOKEN);
        }

        //凭证为空
        if (StrUtil.isBlank(token)) {
            throw new RRException("token不能为空", HttpStatus.UNAUTHORIZED.value());
        }

        request.setAttribute(TOKEN, token);
        return true;
    }
}
